import { ipcMain, BrowserWindow } from 'electron';
import IpcParams, { gEventTonwebCreate } from './IpcParams';
const TonWeb = require('tonweb');
// const tonMnemonic  = require('tonweb-mnemonic');
const Address = TonWeb.utils.Address;


function handleTonwebCall(event, ipcParams) {
  console.log('call', event, ipcParams)
}


async function handleTonwebInvoke(ipcEvent, ipcParams) {

  const { event, params } = ipcParams
  if (event == gEventTonwebCreate) {
    return await createWallet(params.count)
  }

  // console.log(event, ipcParams)
  if (ipcParams.event == "transfer_wallet_to_friendly") {
    return await transfer(ipcParams.params)
  }
}

async function createWallet(count) {
  console.log('createWall ------------------------------------   >>>>>')
  console.log(`todo use tonweb to create ${count} wallet`)




  try {
    // const tonweb = new TonWeb();
    // console.log("todo with tonweb instance", tonweb)
    // const words = await generateMnemonic();
    // tonMnemonic.wordlists.EN;
    // -> array of all words

    // const mnemonic = await tonMnemonic.generateMnemonic();
    console.log('--------------------------')
    console.log(' The Mnemonic : ', mnemonic);
    console.log('--------------------------')
  } catch (error) {
    console.error(error)
  }

  // 生成钱包成功后把钱包的数据传回渲染进程
  // 假如testWallets是你生成的钱包数组

  console.log('');
  // const words = await generateMnemonic();
  // console.log(' The Mnemonic : ', words);


  const testWallets = [
    {
      mnemonic: "abc, asd, ...",
      address: "xxxxxxxx",
      address_user_friendly: "yyyyyyy",
    },
    {
      mnemonic: "abc, asd, ...",
      address: "xxxxxxxx",
      address_user_friendly: "yyyyyyy",
    },
  ]
  // const notifyParams = new IpcParams(gEventTonwebCreate, testWallets)
  // BrowserWindow.getFocusedWindow().webContents.send("tonweb.notify", notifyParams)
}

export function registerOnIpcMain() {
  ipcMain.on("tonweb.call", handleTonwebCall)
  ipcMain.handle("tonweb.invoke", handleTonwebInvoke)
}

export function transfer(wallet_address) {
  const Address = TonWeb.utils.Address
  const address = new Address(wallet_address)
  return address.toString(false, true, true)
}
